package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.system.domain.AlarmRule;
import com.ruoyi.system.domain.AlarmRulePersonVehicle;
import com.ruoyi.system.domain.request.alarmrule.AlarmRulePersonVehicleParam;
import com.ruoyi.system.domain.request.alarmrule.BindAlarmRuleParam;
import com.ruoyi.system.domain.vo.alarmrule.AlarmRuleObject;
import com.ruoyi.system.mapper.AlarmRulePersonVehicleMapper;
import com.ruoyi.system.service.IAlarmRulePersonVehicleService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 告警规则绑定人和车的中间Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class AlarmRulePersonVehicleServiceImpl extends ServiceImpl<AlarmRulePersonVehicleMapper, AlarmRulePersonVehicle> implements IAlarmRulePersonVehicleService {
    @Autowired
    private AlarmRulePersonVehicleMapper alarmRulePersonVehicleMapper;

    @DataScope
    @Override
    public List<AlarmRuleObject> selectList(AlarmRulePersonVehicleParam param) {
        return alarmRulePersonVehicleMapper.list(param);
    }

    /**
     * 绑定监管对象
     * @param param
     */
    @Override
    public void bindObject(BindAlarmRuleParam param){
        if (ObjectUtils.isNotEmpty(param.getUnbindIds())){
            //删除原规则绑定关系
            remove(new QueryWrapper<AlarmRulePersonVehicle>()
                    .eq("alarm_rule_id", param.getAlarmRuleId())
                    .in("business_id", param.getUnbindIds()));
        }
        if (ObjectUtils.isNotEmpty(param.getNewBindIds())){
            //添加现在规则绑定关系
            List<AlarmRulePersonVehicle> alarmRuleList = Arrays.stream(param.getNewBindIds()).map(i ->
                    new AlarmRulePersonVehicle().setAlarmRuleId(param.getAlarmRuleId()).setBusinessId(i)).collect(Collectors.toList());
            saveBatch(alarmRuleList);
        }
    }

    /**
     * 监管对象绑定的报警规则列表
     */
    @Override
    public List<AlarmRule> bindingList(Long objectId){
        return alarmRulePersonVehicleMapper.listBinding(objectId);
    }
}
